var map;
var toolBar;
var points;//轨迹路径
var progress=0;//播放进度
var speed=1000;//播放速度(km/h)
var playIndex=0;//用于标识手动进行修改的播放进度(该变量用于设置播放过的轨迹)
var passedPolyline;//播放过的轨迹路径
var isPlaying=false;//是否正在播放

function initialize() {
	map = new AMap.Map("container", {
		view: new AMap.View2D({ //创建地图二维视口
			center: [116.397428, 39.90923], //创建中心点坐标
			zoom: 5, //设置地图缩放级别
			rotation: 0, //设置地图旋转角度
			resizeEnable: true
		}),
		lang: "zh_cn" //设置地图语言类型，默认：中文简体
	}); //创建地图实例


	//加载标尺
	map.plugin(["AMap.Scale"], function() {
		var scale = new AMap.Scale();
		map.addControl(scale);
	});

	//加载鹰眼
	// map.plugin(["AMap.OverView"], function() {
	// 	var view = new AMap.OverView({
	// 		visible: true
	// 	});
	// 	view.open(); //初始化的时候就展开鹰眼

	// 	map.addControl(view);
	// });
	
	map.plugin(["AMap.ToolBar"], function() {
		toolBar = new AMap.ToolBar();
		map.addControl(toolBar);
	});

	//加载地图类型切换插件
	map.plugin(["AMap.MapType"], function() {
		//地图类型切换
		var mapType = new AMap.MapType({
			defaultType: 0, //默认显示画布地图
			showRoad: true //叠加路网图层
		});
		map.addControl(mapType);
	});
	
	
}

//初始化数据
function initData(){
	points=null;
	progress=playIndex=0;
	try{
		passedPolyline.setPath(null);
	}catch(e){}
	isPlaying=false;
}

// var pts=	"[\"117.590423448351,38.031219618056\",\"117.590301378039,38.031234809028\",\"117.590118543837,38.031250271268\",\"117.589950629341,38.031258138021\",\"117.589844292535,38.031261935764\",\"117.589554307726,38.031281195747\",\"117.589417317709,38.031292588976\",\"117.589302842882,38.031303982205\",\"117.589181043837,38.031315646702\",\"117.589051378039,38.031327311198\",\"117.588929578994,38.031342502171\",\"117.588807508681,38.031357693143\",\"117.588693033855,38.03137342665\",\"117.588586425782,38.031384819879\",\"117.588479546441,38.031396213108\",\"117.588479546441,38.031396213108\",\"117.587275119358,38.03151529948\",\"117.587222222223,38.031522894966\",\"117.587183973525,38.031534288195\",\"117.587168782553,38.031541883681\",\"117.587168782553,38.031549479167\",\"117.587130533855,38.031557345921\",\"117.586818033855,38.031633843316\",\"117.586779785157,38.031630045573\",\"117.58671875,38.03164171007\",\"117.586657986112,38.031656901042\",\"117.586620008681,38.031664496528\",\"117.586589355469,38.031675889757\",\"117.586589355469,38.031683756511\",\"117.586596950955,38.03169514974\",\"117.586612413195,38.031702745226\",\"117.586635199653,38.031710340712\",\"117.586650390625,38.031714138455\",\"117.586673448351,38.031721733941\",\"117.586688639323,38.031714138455\",\"117.586711425782,38.031710340712\",\"117.586719021268,38.031713867188\",\"117.58673421224,38.031710069445\",\"117.586719021268,38.031702745226\",\"117.586726345487,38.031702473959\",\"117.586749403212,38.031694878473\",\"117.586756998698,38.031694878473\",\"117.586604546441,38.031729329428\",\"117.586581759983,38.031733127171\",\"117.586513129341,38.031740993924\",\"117.586474880643,38.03174858941\",\"117.586452365452,38.031752387153\",\"117.586391330296,38.031863064237\",\"117.586368543837,38.031870659723\",\"117.586345486112,38.031885850695\",\"117.586299641928,38.031901312935\",\"117.586269259983,38.031916503907\",\"117.586223687066,38.03192437066\",\"117.586208496094,38.031928168403\",\"117.586200900608,38.031928168403\",\"117.586193305122,38.031928168403\",\"117.586177842882,38.03192437066\",\"117.586155056424,38.03192030165\",\"117.586155056424,38.03192030165\"]";
var graspRoad;
var pathParam = [
		{"x":113.8870867,"y":22.5742264,"sp":19,"ag":0, "tm":1478031031},
		{"x":113.885026,"y":22.5762143,"sp":10,"ag":0, "tm":60},
		{"x":113.8821432,"y":22.5790795,"sp":10,"ag":0,"tm":60},
		{"x":113.8802828,"y":22.5811677,"sp":10,"ag":0,"tm":60},
		{"x":113.8781826,"y":22.5836003,"sp":20.2,"ag":0,"tm":60},
		{"x":113.8761389,"y":22.5857468,"sp":10,"ag":0, "tm":60},
		{"x":113.873704,"y":22.5892482,"sp":43.8,"ag":0, "tm":60},
		{"x":113.8716366,"y":22.5929235,"sp":28.1,"ag":0, "tm":60},
		{"x":113.8691701,"y":22.5965393,"sp":24.7,"ag":0, "tm":60},
		{"x":113.8657459,"y":22.6006089,"sp":10,"ag":0, "tm":60},
		{"x":113.862282,"y":22.6012501,"sp":10,"ag":0, "tm":60}];
//初始化地图
function clearMap () {
	map.clearMap(); //每次加载路线时,清除地图上所有覆盖物,防止覆盖物重复
	initData();
}

function drawTrip(points){
	var polyline = new AMap.Polyline({
		map: map,
		path: points,       
		strokeColor: "#3898f9",//线颜色
		strokeOpacity: 1,//线透明度
		strokeWeight: 4,//线宽
		strokeDasharray:[10,5],
		position:true,
		strokeStyle: "solid"//线样式
		
	});
}


//加载轨迹路径
function newLoadPath(arr){
	// showGps();
	// map.clearMap(); //每次加载路线时,清除地图上所有覆盖物,防止覆盖物重复
	// initData();
	if(!graspRoad) {
			graspRoad = new AMap.GraspRoad();
		}
		for (var i = 0; i < arr.length; i++) {
			drivingLoad(i,arr[i])
		}
	
}

function drivingLoad (key,item) {
	let pathParams=item.tripInfoVoList;
	if(pathParams.length==0){
		myControl.$message.error('没有轨迹信息');
		return false;
	}
	graspRoad.driving(pathParams,function(error,result){
		  if(!error){
			points = [];
			var newPath = result.data.points;
			for(var i =0;i<newPath.length;i+=1){
			  points.push([newPath[i].x,newPath[i].y])
			}
	
			//绘制轨迹
			drawTrip(points);
			//车辆运行过的轨迹
			passedPolyline = new AMap.Polyline({
				map: map,
				strokeColor: "#f74948",	//线颜色
				strokeOpacity: 1,		//线透明度
				strokeWeight: 5,		//线宽		
				position:true,
				strokeStyle: "solid"	//线样式
			});
			//绘制车辆图标
			marker = new AMap.Marker({
				map: map,
				position: points[0],//基点位置
				icon:"http://webapi.amap.com/images/car.png",
				offset: new AMap.Pixel(-26, -13), //相对于基点的位置
				autoRotation: true//自动旋转角度       
			});
			var start_markers=[];
			var end_markers=[];
			var markers=[];
			
			//起点和终点
			start_markers.push({
				icon: new AMap.Icon({
					image: "../images/jsdemo002.png",
					size: new AMap.Size(30, 40),
					imageOffset: new AMap.Pixel(-key*40, -95)
				}),
				position: [parseFloat(points[0].R),parseFloat(points[0].Q)]
			});
			end_markers.push({
				icon: new AMap.Icon({
					image: "../images/jsdemo002.png",
					size: new AMap.Size(30, 30),
					imageOffset: new AMap.Pixel(-key*31, -134)
				}),
				position: [parseFloat(points[points.length-1].R),parseFloat(points[points.length-1].Q)]
			});
			//急加速
			item.rapidAccelerationList.length>0&&$.each(item.rapidAccelerationList,function(key,val){
				markers.push({
					icon: new AMap.Icon({
						image: "../images/speedup.png",
						size: new AMap.Size(44, 44)
					}),
					position: [parseFloat(val.lon),parseFloat(val.lat)]
				});
			});
			//急减速
			item.rapidDecelerationList.length>0&&$.each(item.rapidDecelerationList,function(key,val){
				markers.push({
					icon: new AMap.Icon({
						image: "../images/speedcut.png",
						size: new AMap.Size(44, 44)
					}),
					position: [parseFloat(val.lon),parseFloat(val.lat)]
				});
			});
			//急转弯
			item.sharpTurnList.length>0&&$.each(item.sharpTurnList,function(key,val){
				markers.push({
					icon: new AMap.Icon({
						image: "../images/sharpbend.png",
						size: new AMap.Size(44, 44)
					}),
					position: [parseFloat(val.lon),parseFloat(val.lat)]
				});
			});
			//超速
			item.speedingList.length>0&&$.each(item.speedingList,function(key,val){
				markers.push({
					icon: new AMap.Icon({
						image: "../images/overspeed.png",
						size: new AMap.Size(44, 44)
					}),
					position: [parseFloat(val.lon),parseFloat(val.lat)]
				});
			});
			start_markers.forEach(function(value) {
				var m = new AMap.Marker({
					map: map,
					icon: value.icon,
					position: [value.position[0], value.position[1]],
					offset: new AMap.Pixel(-22, -40), //相对于基点的位置
					title: "始:"+item.startTime.slice(0,19),
					zIndex: 100
				});
				m.on("mouseover",function (e) {
					m.setzIndex(200)
				})
				m.on("mouseout",function (e) {
					m.setzIndex(100)
				})
			});
			end_markers.forEach(function(value) {
				var m = new AMap.Marker({
					map: map,
					icon: value.icon,
					position: [value.position[0], value.position[1]],
					offset: new AMap.Pixel(-22, -40), //相对于基点的位置
					title: "终:"+item.endTime.slice(0,19),
					zIndex: 101
				});
				m.on("mouseover",function (e) {
					m.setzIndex(200)
				})
				m.on("mouseout",function (e) {
					m.setzIndex(101)
				})
			});
		//	setMarkerIcon(icon);
			map.setFitView();
			//播放过的轨迹路径设置为红色
			marker.on('moving',function(e){
				passedPolyline.setPath(points.slice(0,playIndex).concat(e.passedPath));
				// console.log(points.slice(0,playIndex).concat(e.passedPath));
				// map.setFitView();
			});
			
			marker.on('moveend',function(){
				progress+=1.5;
				// console.log(points[progress]);
				window.external.Progress = progress;
				map.panTo(points[progress]);
			});
			map.setZoom(13);
			map.panTo(points[progress]);
		  }
		})
	
}
function showGps () {
	var json = myControl.form;
	$.ajax({
	    type: 'get',   //POST/PUT/DELETE/HEAD...
	    url:globalUrl+"/temp/getTTempGpsVoList",
	    // beforeSend: function(request) { request.setRequestHeader("Authorization",serviceToken);  },
	    data:json,
	    dataType: 'json',	//text/script/xml/json/jsonp
	    // contentType:"application/json; charset=UTF-8",
	    success: function (data) {
			console.log(data);
			var list = [];
			$.each(data.data,function(key,val){
				var a = {};
				var lnglat = [];
				lnglat[0]=parseFloat(val.longitude);
				lnglat[1]=parseFloat(val.latitude);
				a['lnglat']=lnglat;
				a['name']= val.time+'<br>'+Math.floor(Number(val.speed)*100)/100+'km/h';
				if(val.speed>0){
					a['style']=1;//绿色
				}else{
					a['style']=0;//黄色
				}
				list.push(a)
			});
			var mass = new AMap.MassMarks(list, {
				opacity: 0.8,
				zIndex: 111,
				cursor: 'pointer',
				alwaysRender: false,
				style: [{
								url: '../images/icons/point.png',
								anchor: new AMap.Pixel(0, 0),
								size: new AMap.Size(6, 6)
							},{
								url: '../images/icons/point2.png',
								anchor: new AMap.Pixel(0, 0),
								size: new AMap.Size(6, 6)
							}]
			});
			var markersss = new AMap.Marker({content: ' ', map: map});
					
			mass.on('mouseover', function (e) {	
				markersss.setPosition(e.data.lnglat);
				markersss.setLabel({content: e.data.name})
			});
			
			mass.on('mouseout', function (e) {
				markersss.setPosition(e.data.lnglat);
				markersss.setLabel(null)
			});
					
			mass.setMap(map);
	    }
	});
}

function converzuobiao (list) {
	$.each(list,function(key,val){
		AMap.convertFrom(val.lnglat, 'gps', function (status, result) {
		  if (result.info === 'ok') {
		    val.lnglat = result.locations;
		  }
		});
	});
}

//根据后台发送的json坐标字符 转换成高度经纬度对象
function jsonConvertToMapLngLat(json)
{
	map.zoom=18;
    if (json === "[]")
    {
        return;
    }

    //json数组转换一组坐标点
    if (json.indexOf('[') > -1 && json.indexOf(']') > -1 )
    {
        var temparray = eval(json);

        var points = new Array();
        
        for (var i = 0; i < temparray.length; i++)
        {
            var obj = temparray[i];
			if (obj.hasOwnProperty('X') && obj.hasOwnProperty('Y'))
                points[i] = new AMap.LngLat(temparray[i].X, temparray[i].Y);
			else{
				var arr=new Array();
				arr=obj.split(",");
				points[i] = new AMap.LngLat(arr[0],arr[1]); 	
			}
        }
        return points;
    }
    else
    {
        if (json === "{}")
        {
            return;
        }

        // json转单个坐标点
        var pt = eval("(" + json + ")");
		if (pt.hasOwnProperty('X') && pt.hasOwnProperty('Y'))
            var point = new AMap.LngLat(pt.X, pt.Y);
		else{
			var arr=new Array();
			arr=pt.split(",");
			var point = new AMap.LngLat(arr[0], arr[1]);
		}     
        //alert(point);
        return point;
    }
}

//轨迹播放
function moveAlong()
{
	isPlaying=true;
	playIndex=progress;
	passedPolyline.setPath(null);
	marker.moveAlong(points,speed);
	map.panTo(points[progress]);
	map.setZoom(15);
}

//继续播放
function resumeMove(){
	isPlaying=true;
	marker.resumeMove();
}

//暂停播放
function pauseMove(){
	isPlaying=false;
	marker.pauseMove();
}

//重置
function stopMove(){
	progress=playIndex=index=0;
	var pr=points.slice(playIndex);
	marker.moveAlong(pr,speed);
	marker.stopMove();
	passedPolyline.setPath(null);
	marker.pauseMove();
	map.panTo(points[progress]);
}

//回放速度
function setMoveSpeed(s){	
	s=s.value>0?s.value:1;
	speed=1000*s;
	var pr=points.slice(progress);//更改后的播放路径
	playIndex=progress;
	passedPolyline.setPath(points.slice(0,playIndex));//将播放过的路径设置为红色
	marker.moveAlong(pr,speed);//设置播放速度

	map.getCenter(marker);
//	if(!isPlaying)
//		pauseMove();
}

function drawStartAndEndICO(){

    var start_xy = points[0];
    var end_xy = points[points.length - 1];

    //起点、终点图标
    var sicon = new AMap.Icon({
        image: "http://cache.amap.com/lbs/static/jsdemo002.png",
        size: new AMap.Size(44, 44),
        imageOffset: new AMap.Pixel(-334, -180)
    });
    var startmarker = new AMap.Marker({
        icon: sicon, //复杂图标
        visible: true,
        position: start_xy,
        map: map,
        offset: {
            x: -16,
            y: -40
        }
    });

    var eicon = new AMap.Icon({
        image: "http://cache.amap.com/lbs/static/jsdemo002.png",
        size: new AMap.Size(44, 44),
        imageOffset: new AMap.Pixel(-334, -134)
    });

    var endmarker = new AMap.Marker({
        icon: eicon, //复杂图标
        visible: true,
        position: end_xy,
        map: map,
        offset: {
            x: -16,
            y: -40
        }
    });
    map.setFitView();
}


